package com.liujun.spring4.demo.aop.aop.introductionInterceptor;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;

/**
 * @author liujun
 * @version 0.0.1
 * @date 2018/09/22
 */
public class ControllablePerformanceMonitor extends DelegatingIntroductionInterceptor
    implements Monitorable {

  /**
   * 使用threadLocal控制状态，因为这个控制使代理代变成为非线程安全的实例，
   *
   * <p>为了解决单实例线程安全的问题，
   *
   * <p>通过ThreadLocal让每个线程单独使用一个状态
   */
  private ThreadLocal<Boolean> monorStatusMap = new ThreadLocal<>();

  @Override
  public void setMonitorActive(boolean active) {
    this.monorStatusMap.set(active);
  }

  @Override
  public Object invoke(MethodInvocation mi) throws Throwable {
    Object obj = null;
    // 判断性能监控是否打开
    if (monorStatusMap.get() != null && monorStatusMap.get()) {
        PerformanceMonitor.begin(mi.getClass().getName()+"."+mi.getMethod().getName());
        obj = super.invoke(mi);
        PerformanceMonitor.end();
    }
    else
    {
        obj = super.invoke(mi);
    }

    return obj;
  }
}
